package com.spring.arthas.controller;

import com.alibaba.fastjson.JSONObject;
import com.spring.arthas.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuzhiqiang
 */
@RestController
@CrossOrigin
@Slf4j
public class TestController {

    @Autowired
    private List<TestService> serviceList;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/test")
    public String test() {
        for (TestService testService : serviceList) {
            testService.test();
        }
        AAA();
        return "true";
    }

    public static void AAA() {
        System.out.println("xxx");
        System.out.println("Ddd");
    }


    /**
     * jad 反编译文件为java
     * mc 编辑Java文件为class
     * retransform 加载外部的.class文件，retransform jvm 已加载的类。
     *
     * @return
     */
    @GetMapping("/jad")
    public String jad() {
        String command = "--source-only com.spring.arthas.service.TestServiceImpl";
        String codeTest = "log.info(\"第一步\");\n" +
                "log.info(\"第二步\");\n" +
                "log.info(\"第三步\");\n" +
                "log.info(\"插入代码块占位\");";


        // 反编译文件得到java文本
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-type", "application/json; charset=utf-8");
        requestHeaders.add("Authorization", "Basic bGl1emhpcWlhbmc6MTIzNDU2");
        Map<String, Object> body = new HashMap<>();
        body.put("action", "exec");
        body.put("requestId", "spring-arthas");
        body.put("command", "jad " + command);
        body.put("execTimeout", "10000");
        HttpEntity<Map> requestEntity = new HttpEntity<>(body, requestHeaders);
        ResponseEntity<String> entity = restTemplate.exchange("http://172.16.190.63:8563/api", HttpMethod.POST, requestEntity, String.class);
        String jsonStr = entity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String javaText = ((JSONObject) jsonObject.getJSONObject("body").getJSONArray("results").get(0)).getString("source");

        javaText = javaText.replace("log.info(\"插入代码块占位\");", codeTest);

        // cm
        String classFilePath = cm(javaText);
        // retransform
        retransform(classFilePath);
        return javaText;
    }

    /**
     * retransform
     *
     * @param classFilePath
     * @return
     */
    private String retransform(String classFilePath) {
        classFilePath = classFilePath.replaceAll("\\\\", "/");
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-type", "application/json; charset=utf-8");
        requestHeaders.add("Authorization", "Basic bGl1emhpcWlhbmc6MTIzNDU2");
        Map<String, Object> body = new HashMap<>();
        body.put("action", "exec");
        body.put("requestId", "spring-arthas");
        body.put("command", "retransform " + classFilePath);
        body.put("execTimeout", "10000");
        HttpEntity<Map> requestEntity = new HttpEntity<>(body, requestHeaders);
        ResponseEntity<String> entity = restTemplate.exchange("http://172.16.190.63:8563/api", HttpMethod.POST, requestEntity, String.class);
        File file = new File(classFilePath);
        file.delete();
        String jsonStr = entity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        return "";
    }

    public String cm(String javaText) {

        try {
            File file = new File("TestServiceImpl.java");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file.getName(), false);
            fileWriter.write(javaText);
            fileWriter.close();

            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-type", "application/json; charset=utf-8");
            requestHeaders.add("Authorization", "Basic bGl1emhpcWlhbmc6MTIzNDU2");
            Map<String, Object> body = new HashMap<>();
            body.put("action", "exec");
            body.put("requestId", "spring-arthas");
            body.put("command", "mc TestServiceImpl.java");
            body.put("execTimeout", "10000");
            HttpEntity<Map> requestEntity = new HttpEntity<>(body, requestHeaders);
            ResponseEntity<String> entity = restTemplate.exchange("http://172.16.190.63:8563/api", HttpMethod.POST, requestEntity, String.class);
            // 删除文件
            file.delete();
            String jsonStr = entity.getBody();
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            String classFilePath = jsonObject.getJSONObject("body").getJSONArray("results").getJSONObject(0).getJSONArray("files").getString(0);
            return classFilePath;
        } catch (Exception e) {
            return null;
        }
    }
}
